package com.xiexie.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiexie.seckill.pojo.Order;
import com.xiexie.seckill.mapper.OrderMapper;
import com.xiexie.seckill.pojo.SeckillGoods;
import com.xiexie.seckill.pojo.SeckillOrder;
import com.xiexie.seckill.pojo.User;
import com.xiexie.seckill.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiexie.seckill.service.ISeckillGoodsService;
import com.xiexie.seckill.service.ISeckillOrderService;
import com.xiexie.seckill.utils.MD5Util;
import com.xiexie.seckill.utils.UUIDUtil;
import com.xiexie.seckill.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 *  服务实现类
 *
 * @author xiexie
 * @date 2021-07-31
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private ISeckillGoodsService seckillGoodsService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional
    @Override
    public Order seckill(User user, GoodsVo goodsVo) {
        // 秒杀商品表减库存
        SeckillGoods seckillGoods = seckillGoodsService.getOne(
                new QueryWrapper<SeckillGoods>()
                        .eq("goods_id", goodsVo.getId())
        );
        //seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        //seckillGoodsService.updateById(seckillGoods);
        boolean updateResult = seckillGoodsService.update(
                new UpdateWrapper<SeckillGoods>()
                        .setSql("stock_count = stock_count - 1")
                        .eq("id", seckillGoods.getId())
                        .gt("stock_count", 0)
        );

        //if (!updateResult) {
        //    return null;
        //}

        // 判断是否还有库存  没有库存 后面秒杀失败
        if (seckillGoods.getStockCount() < 1) {
            redisTemplate.opsForValue().set("isStockEmpty:" + goodsVo.getId(), "0");
            return null;
        }

        // 生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);

        // 生成秒杀订单 加商品和用户的唯一索引 防止同一个人抢到多个商品
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(goodsVo.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrderService.save(seckillOrder);

        String key = "order:" + user.getId() + ":" + goodsVo.getId();
        redisTemplate.opsForValue().set(key, seckillGoods);
        return order;
    }

    /**
     * 获取真实秒杀地址
     *
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, Long goodsId) {
        String path = MD5Util.md5(UUIDUtil.uuid() + "123456");
        String key = "seckillPath:" + user.getId() + ":" + goodsId;
        redisTemplate.opsForValue().set(key, path, 60, TimeUnit.SECONDS);
        return path;
    }

    /**
     * 判断秒杀地址是否存在
     *
     * @param user
     * @param goodsId
     * @param path
     * @return
     */
    @Override
    public boolean checkPath(User user, Long goodsId, String path) {
        if (null == user || goodsId < 0 || StringUtils.isBlank(path)) {
            return false;
        }
        String key = "seckillPath:" + user.getId() + ":" + goodsId;
        String redisPath = (String) redisTemplate.opsForValue().get(key);
        return redisPath.equals(path);
    }

    /**
     * 验证 captcha
     *
     * @param user
     * @param goodsId
     * @param captcha
     */
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        String key = "captcha:" + user.getId() + ":" + goodsId;
        String redisCaptcha = (String) redisTemplate.opsForValue().get(key);
        return redisCaptcha.equals(captcha);
    }
}
